package net.nagaseyasuhito.nicola;

import javax.persistence.NoResultException;

import net.nagaseyasuhito.nicola.entity.User;
import net.nagaseyasuhito.nicola.service.UserService;

import org.apache.wicket.Request;
import org.apache.wicket.authentication.AuthenticatedWebApplication;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.Roles;

public class NicolaSession extends AuthenticatedWebSession {
	private static final long serialVersionUID = 1L;

	private Long userId;

	public static NicolaSession get() {
		return (NicolaSession) AuthenticatedWebSession.get();
	}

	public NicolaSession(AuthenticatedWebApplication application, Request request) {
		super(application, request);
	}

	public User getUser() {
		return this.getUserService().findById(this.userId);
	}

	public UserService getUserService() {
		return NicolaWebApplication.get().getInjector().getInstance(UserService.class);
	}

	@Override
	public boolean authenticate(String name, String password) {
		try {
			User user = this.getUserService().findByNameAndPassword(name, password);
			this.userId = user.getId();
			return true;
		}
		catch(NoResultException e) {
			return false;
		}
	}

	@Override
	public void signOut() {
		super.signOut();

		this.userId = null;
	}

	@Override
	public Roles getRoles() {
		return this.userId != null?new Roles("user"):null;
	}
}
